package cn.sm1234.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Bean
    public JedisPoolConfig getJedisPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
//        // 最大空闲数量
//        poolConfig.setMaxIdle(5);
//        poolConfig.setMaxIdle(3);
//        // 最大连接数
//        poolConfig.setMaxTotal(10);
        return poolConfig;
    }

    @Bean
    public JedisConnectionFactory getJedisConnectionFactory(JedisPoolConfig poolConfig){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setPoolConfig(poolConfig);
//        jedisConnectionFactory.setHostName("127.0.0.1");
//        jedisConnectionFactory.setPort(6379);
//        jedisConnectionFactory.setDatabase(1);
        return jedisConnectionFactory;
    }

    // 这里这个名字redidsTemplate不能写getRedisTemplate，因为可能会名字冲突 。 近而写入redis有前缀乱码
    @Bean
    public RedisTemplate<String , Object> redisTemplate(JedisConnectionFactory connectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // 设置KEY序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置值序列化
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}
